import Vue from 'vue'
import fetch from '@/utils/network/fetch'
import cloneDeep from 'lodash/cloneDeep'
import isEqual from 'lodash/isEqual'
import defaultEmptyBusiness from '@/pages/course/data/init/business'
import api from '@/api'

const state = {
    businessTemplates: [],
    // *** add by james ***
    businessTemplate: null,
    appTemplate: null,
    counterTemplate: null,
    counterTemplates: [],
    counters: null,
    // *******************
    activedEditor: null,
    activedConfig: null,
    activedItem: null,
    activedZone: null,
    activedApp: null,
    // *******************
    counter: null,
    business: null,
    // *******************
    apps: null,
    previewApps: null,
    origin: {
        counter: null,
        business: null,
        apps: null
    }
}

const getters = {
    modified: state => {
        return {
            counter: !isEqual(state.counter, state.origin.counter),
            business: !isEqual(state.business, state.origin.business),
            apps: !isEqual(state.apps, state.origin.apps)
        }
    }
}

const actions = {
    save({ dispatch, commit }) {
        commit('cache')
    },
    getCounterById({ commit }, id) {
        id &&
        fetch(`/api/counter/${id}`, {
            success: counterTemplate => commit('setCounterTemplate', { counterTemplate })
        })
    },
    getBusinessById({ commit }, id) {
        id &&
        fetch(`/api/business_template/${id}`, {
            success: businessTemplate => {
                commit('setBusinessTemplate', { businessTemplate })
                commit('cache')
            }
        })
    },
    getCounters({ commit }) {
        fetch('/api/counter', {
            loading: false,
            success: res => {
                commit('setCounters', { counterTemplates: res.content })
            },
            method: 'post',
            data: {}
        })
    },
    saveCounter({ state, commit, dispatch }, counter) {
        if (!counter) return
        state.counterTemplate.content = JSON.stringify(counter)
        state.counterTemplate.name = counter.name
        fetch('/api/counter', {
            success: counterTemplate => {
                commit('setCounterTemplate', { counterTemplate })
                commit('cache')
                dispatch('getCounters')
            },
            method: 'put',
            data: state.counterTemplate
        })
    },
    saveBusinessTemplate({ state, commit }) {
        state.business.totalScore = getTotalScore(state.business)
        state.businessTemplate.businessAudioUrl = state.business.businessAudioUrl
        state.businessTemplate.businessVideoUrl = state.business.businessVideoUrl
        state.business.name = state.businessTemplate.name
        state.business.apps && clearTransSystemItemValue(state.business.apps)
        state.businessTemplate.content = JSON.stringify(state.business)
        state.businessTemplate &&
        state.businessTemplate.content &&
        fetch('/api/business_template', {
            success: businessTemplate => {
                commit('setBusinessTemplate', { businessTemplate })
                commit('cache')
            },
            method: 'put',
            data: state.businessTemplate
        })
    },
    getBusinessesByTrainingId({ commit }, { trainingId, businessId }) {
        trainingId &&
        fetch(`/api/training/${trainingId}`, {
            loading: false,
            success: training => {
                let businessTemplates = api.getBusinessTemplatesFromTraining(training)
                commit('update', { businessTemplates })
                const businessTemplate = businessTemplates.find(templ => templ.id == businessId)
                commit('setBusinessTemplate', { businessTemplate: businessTemplate ? businessTemplate : businessTemplates[0] })
                commit('cache')
            }
        })
    },
    getBusinessesByExamPaperId({ commit }, { examPaperId, businessId }) {
        examPaperId &&
        fetch(`/api/exam_paper/${examPaperId}`, {
            loading: false,
            success: examPaper => {
                const businessTemplates = examPaper.businessTemplates
                commit('update', { businessTemplates })
                const businessTemplate = businessTemplates.find(templ => templ.id == businessId)
                commit('setBusinessTemplate', { businessTemplate: businessTemplate ? businessTemplate : businessTemplates[0] })
                commit('cache')
            }
        })
    },
    completeExam({ commit }, examId) {
        examId &&
        fetch(`/api/exam/completion/${examId}`, {
            promptMessage: '已记录本次业务考试',
            loading: false,
            method: 'put'
        })
    },
    submitExamStepResult({ commit }, examResults) {
        examResults &&
        fetch('/api/record/examination', {
            loading: false,
            promptMessage: '业务考试结果已提交',
            method: 'put',
            data: examResults
        })
    },
    submitLearningStepResult({ commit }, learningResults) {
        learningResults &&
        fetch('/api/record/learning', {
            loading: false,
            promptMessage: '业务学习结果已提交',
            method: 'put',
            data: learningResults
        })
    }
}

const mutations = {
    setPreviewApps: (state, apps) => {
        state.previewApps = apps
    },
    setBusinessTemplate: (state, payload) => {
        let { businessTemplate } = payload
        setCurrentBusinessTemplate(state, businessTemplate)
    },
    changeBusiness: (state, businessId) => {
        if (state.businessTemplates) {
            for (const businessTemplate of state.businessTemplates) {
                if (businessTemplate.id == businessId) {
                    setCurrentBusinessTemplate(state, businessTemplate)
                    return
                }
            }
        }
    },
    setBusinessStep: (state, payload) => {
        console.log(payload)
        const { step, index } = payload
        if (step && index === undefined) {
            state.business.steps.push(step)
        }
        if (step && index !== undefined) {
            state.business.steps[index] = step
        }
        if (!step && index !== undefined) {
            state.business.steps.splice(index, 1)
        }
        state.business.steps.sort((a, b) => a.pages - b.pages)
    },
    setCounterBackground: (state, payload) => {
        state.counter.background = payload.counter.background
        state.business.counter.background = payload.counter.background
    },
    setCounter: (state, payload) => {
        state.counter = payload.counter
        state.business.counter = payload.counter
    },
    setCounterTemplate: (state, payload) => {
        state.counterTemplate = payload.counterTemplate
        // 如果保存的柜台数据为空，初始化空白柜台模版
        state.counter =
            state.counterTemplate && state.counterTemplate.content
                ? JSON.parse(state.counterTemplate.content)
                : defaultEmptyBusiness.counter
    },
    setCounters: (state, payload) => {
        state.counterTemplates = payload.counterTemplates
        state.counters = state.counterTemplates
            ? state.counterTemplates.map(temp =>
                temp.content
                    ? JSON.parse(temp.content)
                    : { ...defaultEmptyBusiness.counter, name: temp.name }
            )
            : []
    },
    setAppTemplate: (state, payload) => {
        state.appTemplate = payload.appTemplate
        state.apps =
            state.appTemplate && state.appTemplate.content
                ? JSON.parse(state.appTemplate.content)
                : defaultEmptyBusiness.apps
        state.activedApp = state.apps[0]
    },
    // **********************
    cache: (state, payload) => {
        Vue.set(state.origin, 'counter', cloneDeep(state.counter))
        Vue.set(state.origin, 'business', cloneDeep(state.business))
        Vue.set(state.origin, 'apps', cloneDeep(state.apps))
    },
    update: (state, payload) => {
        if (payload.activedItem && !payload.activedItem.uid) {
            payload.activedItem.uid = getUid()
        }
        Object.assign(state, payload)
    },
    addActivedApp: (state, payload) => {
        Object.assign(state.apps, [...state.apps, payload])
    },
    delActivedApp: (state, payload) => {
        state.apps = state.apps.filter(app => app.name !== payload.name)
        state.business.apps = state.apps
    },
    updateActivedApp: (state, payload) => {
        state.apps.forEach(app => {
            if (app.name === payload.name) {
                Object.assign(app, payload)
            }
        })
    },
    updateActivedItem: (state, payload) => {
        if (!payload.uid) {
            payload.uid = getUid()
        }
        state.activedItem = payload
    },
    addActivedItem: (state, payload) => {
        if (!payload.uid) {
            payload.uid = getUid()
        }
        const prevActivedItem = state.activedItem
        state.activedItem = payload
        if (state.activedEditor === 'counter') {
            state.counter.items.push(payload)
        }
        if (state.activedEditor === 'business') {
            if (prevActivedItem) {
                let index = -1
                for (let i = 0; i < state.business.scripts.length; ++i) {
                    if (state.business.scripts[i].uid == prevActivedItem.uid) {
                        index = i
                        break
                    }
                }
                if (index >= 0 && index < state.business.scripts.length) {
                    state.business.scripts.splice(index + 1, 0, payload)
                    return
                }
            }
            state.business.scripts.push(payload)
        }
        if (state.activedEditor === 'apps') {
            let actviedApp = state.apps.find(app => app.name === state.activedApp)
            actviedApp.items.push(payload)
        }
    },
    delActivedItem: state => {
        const { uid } = state.activedItem
        state.activedItem = null
        if (state.activedEditor === 'counter') {
            state.counter.items = state.counter.items.filter(item => item.uid !== uid)
        }
        if (state.activedEditor === 'business') {
            state.business.scripts = state.business.scripts.filter(item => item.uid !== uid)
        }
        if (state.activedEditor === 'apps') {
            const actviedApp = state.apps.find(app => app.name === state.activedApp)
            actviedApp.items = actviedApp.items.filter(item => item.uid !== uid)
        }
    },
    updateCounterZones: (state, payload) => {
        const { key, value } = payload
        Object.assign(state.counter, { [key]: value })
    },
    rotateDesktopArea: (state, payload) => {
        state.counter.desktopArea.rotate = payload
    }
}

function setCurrentBusinessTemplate(state, businessTemplate) {
    state.businessTemplate = businessTemplate
    // 如果保存的模版数据为空，初始化空白业务模版
    state.business = businessTemplate.content
        ? JSON.parse(businessTemplate.content)
        : { ...defaultEmptyBusiness, name: businessTemplate.name }
    state.business = { ...state.business, ...getSecondsOfGrade(businessTemplate) }
    state.counter = state.business.counter
        ? state.business.counter
        : defaultEmptyBusiness.counter
    state.apps = state.business.apps
}

function getUid() {
    return (Math.random() + 1).toString(36).substring(7)
}

function getTotalScore(business) {
    let score = 0
    if (business.scripts && business.scripts.length > 0) {
        business.scripts.forEach(script => {
            const { onChange, onDrag, onClick } = script
            score += onChange && onChange.score ? onChange.score : 0
            score += onDrag && onDrag.score ? onDrag.score : 0
            score += onClick && onClick.score ? onClick.score : 0
        })
    }
    if (business.apps && business.apps.length > 0) {
        business.apps.forEach(app => {
            Array.isArray(app.events) && app.events.forEach(event => {
                score += event.score ? event.score : 0
            })
            app.items && app.items.forEach(item => {
                score += item.onChange && item.onChange.score ? item.onChange.score : 0
                score += item.onClick && item.onClick.score ? item.onClick.score : 0
            })

            const { onChange, onClick } = app
            score += onChange && onChange.score ? onChange.score : 0
            score += onClick && onClick.score ? onClick.score : 0
        })
    }
    console.log('getTotalScore', score)
    return score
}

function getSecondsOfGrade(businessTemplate) {
    const {
        timeCostMinutesExcellent,
        timeCostMinutesGood,
        timeCostMinutesNormal,
        timeCostSecondsExcellent,
        timeCostSecondsGood,
        timeCostSecondsNormal
    } = businessTemplate
    return {
        excellent: getSeconds(timeCostMinutesExcellent, timeCostSecondsExcellent),
        good: getSeconds(timeCostMinutesGood, timeCostSecondsGood),
        normal: getSeconds(timeCostMinutesNormal, timeCostSecondsNormal)
    }
}

function getSeconds(minutes, seconds) {
    let resultSeconds = minutes ? Number(minutes) * 60 : 0
    resultSeconds += seconds ? Number(seconds) : 0
    return resultSeconds
}

function clearTransSystemItemValue(apps) {
    if (apps) {
        for (let app of apps) {
            for (let item of app.items) {
                if (item.type == 'input' && item.value) {
                    item.value = undefined
                } else if (item.type == 'select' && item.value) {
                    item.value = undefined
                }
            }
        }
    }
}

export default {
    course: {
        namespaced: true,
        state,
        getters,
        actions,
        mutations
    }
}
